﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ServiceModel;

namespace Elf.Data.Entity.Management
{
    /// <summary>
    /// The WCF db context manager. This class is not thread safe.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class WcfDbContextManager<T> : DbContextManager<T>
        where T : ContextBase, new()
    {
        private object _lockObject;

        /// <summary>
        /// Returns a shared ObjectContext instance.
        /// </summary>
        public override T DbContext
        {
            get
            {
                lock (_lockObject)
                {
                    if (ApplicationRequestContext.Current.DbContext == null)
                    {
                        ApplicationRequestContext.Current.DbContext = new T();
                    }
                }
                return ApplicationRequestContext.Current.DbContext as T;
            }
        }


        /// <summary>
        /// Initializes a new instance of the <see cref="WcfDbContextManager&lt;T&gt;"/> class.
        /// </summary>
        public WcfDbContextManager()
        {
            if (OperationContext.Current == null)
                throw new InvalidOperationException("This class can only be used in a WCF context.");

            _lockObject = new object();
        }
    }
}
